package com.bear.hospital.controller;

/**
 * @Author： zmwx
 * @Date： 2025/2/12 14:47
 * @Describe：
 */

import com.bear.hospital.config.MinioConfig;
import com.bear.hospital.service.minio.MinioService;
import com.bear.hospital.utils.ResponseData;
import io.minio.BucketArgs;
import io.minio.BucketExistsArgs;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.errors.*;
import io.minio.messages.Bucket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/files")
@Slf4j
public class FileController {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioService minioService;
    @Autowired
    MinioConfig minioConfig;

    @PostMapping("/upload")
    public ResponseData uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            minioService.uploadFile(minioConfig.getBucketName(), file);
            return ResponseData.success("文件上传成功");
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return ResponseData.fail(e.getMessage());
        }
    }

    @PostMapping("/uploadImage")
    public ResponseData uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            String imageUrl = minioService.uploadImage(minioConfig.getBucketName(), file);
            return ResponseData.success("图片上传成功", imageUrl);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return ResponseData.fail(e.getMessage());
        }
    }

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadImage(@RequestParam String fileName) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        InputStreamResource resource = new InputStreamResource(minioClient.getObject(GetObjectArgs.builder().bucket("bucket-name").object(fileName).build()));
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }
        @GetMapping("/test-minio")
    public String testMinioConnection() {
        try {
            boolean isBucketExist  = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConfig.getBucketName()).build());
            // Check if the bucket exists or not.
            return isBucketExist ? "Successfully connected to MinIO and bucket exists" : "Bucket does not exist";
        } catch (Exception e) {
            e.printStackTrace();
            return "Failed to connect to MinIO due to an error.";
        }

    }
    @GetMapping("/list-buckets")
    public List<String> listBuckets() {
        try {
            // 列出所有的存储桶
            List<Bucket> buckets = minioClient.listBuckets();
            log.error("Bucket list: " + buckets);
            return buckets.stream().map(Bucket::name).collect(Collectors.toList());
        } catch (XmlParserException e) { // 捕获具体的XML解析异常
            // 记录详细的错误日志
            System.err.println("Failed to parse XML response from MinIO: " + e.getMessage());
            // 可能需要进一步调查或修复XML格式的问题
            return Collections.emptyList(); // 返回空列表而不是null
        } catch (MinioException | IOException | InvalidKeyException | NoSuchAlgorithmException e) {
            // 记录其他类型的异常
            System.err.println("An error occurred while listing buckets: " + e.getMessage());
            return Collections.emptyList(); // 返回空列表而不是null
        }
    }
}